<script setup lang="ts">
import { genDelConfs } from '../../utils'
import { TypeOptions, FormItemShow, FormValidateRules } from './conf'

const { success = () => {} } = defineProps<{
  success?: () => void
}>()

const form = defineModel<ScriptConfType>('form', { default: genScriptConf() })

const formItemShow = computed(() => FormItemShow[form.value.type])
const formRules = computed(() => FormValidateRules[form.value.type])

const scriptConfStore = useScriptConfStore()

// 新增配置数据时，根据配置类型设置默认图标
watch(
  () => form.value?.type,
  () => {
    if (form.value?._id) return
    form.value.icon = genScriptConfDefaultIcon(form.value.type)
  }
)

const currentIsDirForm = () => form.value.type === ScriptConfTypeConst.DIR

const delConfs = genDelConfs()

const formBaseRef = ref()
const validate = async () => await formBaseRef.value.isValidatePass()
const [isSaving, saveScriptConf] = genSubmitFormHandler({
  beforeSubmit: validate,
  handleSubmit: async () => {
    return await api.saveScriptConfs([
      {
        ...toRaw(form.value),
        parent: formBaseRef.value.formItemParentRef.getParentPropValue()
      }
    ])
  },
  afterSubmit: async (res) => {
    await scriptConfStore.load()
    if (res.status) success()
    tipByResult(res)
  }
})
</script>

<template>
  <form-base
    ref="formBaseRef"
    :rules="formRules"
    :model="form"
    :form-item-show="formItemShow"
    :conf-type-options="TypeOptions"
    :current-is-dir-form="currentIsDirForm"
    :get-dir-tree="scriptConfStore.getDirTree"
  >
    <template #operations-pre>
      <del-btn
        v-if="form?._id"
        :btn-props="{
          type: 'danger',
          text: false
        }"
        :dir="currentIsDirForm()"
        :confirm="(cascade) => delConfs(form?._id as string, cascade, success)"
      />
    </template>
    <template #operations-suf="{ collapse }">
      <div class="flex items-center gap-2">
        <save-btn
          :collapse="collapse"
          :btn-props="{
            disabled: isSaving,
            loading: isSaving
          }"
          :click="saveScriptConf"
        />
      </div>
    </template>
  </form-base>
</template>

<style scoped lang="scss"></style>
